<template>
  <div class="map-container">
    <div ref="mapChart" class="map-chart"></div>

    <el-dialog
      v-model="dialogVisible"
      :title="`${selectedProvince}特色菜谱`"
      width="50%"
    >
      <div>
        <div v-if="recipeList.length > 0" class="recipe-list">
          <div v-for="recipe in recipeList" :key="recipe.cookbId" class="recipe-item">
            <el-image 
              v-if="recipe.recipeImg" 
              :src="recipe.recipeImg" 
              fit="cover"
              class="recipe-image"
            />
            <div class="recipe-info">
              <h3>{{ recipe.cookbName }}</h3>
              <p>{{ recipe.cuisine }} · {{ recipe.place }}</p>
              <el-button size="small" type="primary" @click="viewRecipeDetail(recipe)">查看详情</el-button>
            </div>
          </div>
        </div>
        <el-empty v-else description="暂无该地区的菜谱" />
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="handleAddRecipe">没有想要的菜谱？去添加</el-button>
        </span>
      </template>
    </el-dialog>
  </div>



      <Dialog :title="dialog.title" :width="dialog.width" :height="dialog.height" :visible="dialog.visible"
        @on-close="onClose" @on-confirm="commit">

        <el-form :model="addfoodform" ref="addFormRef" :rules="rule">
            <!-- 菜谱名字 -->
            <el-form-item label="菜谱名字" prop="cookbName">
                <el-input v-model="addfoodform.cookbName" placeholder="请输入菜谱名称" />
            </el-form-item>

            <!-- 菜系 -->
            <el-form-item label="菜系" prop="cuisine">
                <el-select v-model="addfoodform.cuisine" placeholder="请选择所属菜系" clearable>
                    <el-option v-for="item in cuisineOptions" :key="item.value" :label="item.label"
                        :value="item.value" />
                </el-select>
            </el-form-item>

            <!-- 地方 -->
            <el-form-item label="地方" prop="place">
                <el-input v-model="addfoodform.place" placeholder="请输入所处地区" />
            </el-form-item>

            <!-- 做法内容 -->
            <el-form-item label="做法内容" prop="content">
                <el-input v-model="addfoodform.content" placeholder="请输入详细做法内容" />
            </el-form-item>

            <UploadImg ref="imageUploader"></UploadImg>

        </el-form>

    </Dialog>
</template>

<script setup lang="ts">
import Dialog from '@/components/dialog/Dialog.vue';
import UploadImg from '@/components/upload/UploadImg.vue';
import { ref, onMounted, onUnmounted, reactive } from 'vue'
import * as echarts from 'echarts'
import axios from 'axios'
import { ElDialog, ElButton, ElEmpty, ElImage, type FormInstance, ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { StatusType, type FoodTable } from '@/api/food/foodTable'
import { addRecipeApi, getRecipeApi } from '@/api/food'
import { useFoodStore } from '@/store/comment'
import useDialog from '@/hooks/usedialog'
import { useImageUrlStore } from '@/store/imgUrl'
import { useUserStore } from '@/store/islogin'
//获取图片store
const userUrlStore = useImageUrlStore()
//获取用户信息store
const useUser = useUserStore()
//获取菜谱信息store
const useFood = useFoodStore()
//获取form表单组件实例
const addFormRef = ref<FormInstance>();
//弹框参数
const { dialog, onClose, onConfirm, onShow } = useDialog()
//添加菜谱列表参数
const addfoodform = reactive({
    cookbId: '',
    userId: '',
    adminId: '',
    cookbName: '',
    cuisine: '',
    place: '',
    content: '',
    recipeImg: '',
    createTime: '',
    updateTime: '',
    status: StatusType.Prohibit,
    reviewedTime: '',
    commentCount: 0,
    favoriteCount: 0
})
// 定义表单验证规则对象
const rule = reactive({
    cookbName: [
        { required: true, message: '请输入菜谱名称', trigger: ['blur', 'change'] },
        { min: 3, max: 15, message: '菜谱名称长度应在3到15个字符之间', trigger: ['blur', 'change'] }
    ],
    cuisine: [
        { required: true, message: '请输入所属菜系', trigger: ['blur', 'change'] }
    ],
    place: [
        { required: true, message: '请输入所处地区', trigger: ['blur', 'change'] }
    ],
    content: [
        { required: true, message: '请输入详细做法内容', trigger: ['blur', 'change'] },
        { min: 10, message: '做法内容不能少于10个字符', trigger: ['blur', 'change'] }
    ]
})
const cuisineOptions = reactive([
    { value: '川菜', label: '川菜' },
    { value: '湘菜', label: '湘菜' },
    { value: '粤菜', label: '粤菜' },
    { value: '闽菜', label: '闽菜' },
    { value: '苏菜', label: '苏菜' },
    { value: '浙菜', label: '浙菜' },
    { value: '徽菜', label: '徽菜' },
    { value: '鲁菜', label: '鲁菜' },
    { value: '其他', label: '其他' }
]);
//表单提交
const commit = () => {
    //表单验证
    addFormRef.value?.validate(async (valid) => {
        if (valid) {
            if (userUrlStore.getImageUrl) {
                addfoodform.recipeImg = userUrlStore.getImageUrl
                if (useUser.user?.userId) { addfoodform.userId = useUser.user?.userId }
                const res = await addRecipeApi(addfoodform)
                userUrlStore.deleteImageUrl()
                if (res.code == 200) {
                    ElMessage.success("添加成功")
                    userUrlStore.deleteImageUrl()
                    // 提交数据...
                    // 提交成功后清空表单：
                    // 调用 resetFields 时用可选链
                    addFormRef.value?.resetFields()
                    onClose()
                }
            } else {
                ElMessage.error("请添加图片")
                return
            }
        }
    });
}

const router = useRouter()

// 地图容器和实例引用
const mapChart = ref<HTMLElement | null>(null)
let chart: echarts.ECharts | null = null

// 弹窗相关状态
const dialogVisible = ref(false)
const selectedProvince = ref('')
const recipeList = ref<FoodTable[]>([])
const loading = ref(false)

// 搜索参数
const searchParams = reactive<FoodTable>({
  cookbId: '',
  userId: '',
  adminId: '',
  cookbName: '',
  cuisine: '',
  place: '',
  content: '',
  recipeImg: '',
  createTime: '',
  updateTime: '',
  status: StatusType.Prohibit,
  reviewedTime: '',
  commentCount: 0,
  favoriteCount: 0
})

// 省份简化函数
function simplifyProvinceName(name: string): string {
  if (name.endsWith('特别行政区')) return name.replace('特别行政区', '')
  if (name.endsWith('壮族自治区')) return name.replace('壮族自治区', '')
  if (name.endsWith('回族自治区')) return name.replace('回族自治区', '')
  if (name.endsWith('维吾尔自治区')) return name.replace('维吾尔自治区', '')
  if (name.endsWith('自治区')) return name.replace('自治区', '')
  if (name.endsWith('省')) return name.replace('省', '')
  if (name.endsWith('市')) return name.replace('市', '')
  return name
}

// 获取菜谱数据
const fetchRecipes = async (province: string) => {
  loading.value = true
  try {
    searchParams.place = province
    const res = await getRecipeApi(searchParams)
    if (res.code === 200) {
      recipeList.value = res.data
    }
  } catch (error) {
    console.error('获取菜谱失败:', error)
    recipeList.value = []
  } finally {
    loading.value = false
  }
}
// 跳转到添加菜谱页面
const handleAddRecipe = () => {
  onShow()
}

// 查看详情方法，具体逻辑由你实现
function viewRecipeDetail(recipe: FoodTable) {
  useFood.setSelectedFood(recipe)
  router.push("/comment")
  // TODO: 实现查看详情逻辑
}

// 初始化地图
const initChart = async () => {
  if (!mapChart.value) return
  try {
    chart = echarts.init(mapChart.value)
    const { data: chinaJson } = await axios.get('https://geo.datav.aliyun.com/areas_v3/bound/100000_full.json')
    echarts.registerMap('china', chinaJson)

    chart.setOption({
      title: {
        text: '中国地图',
        left: 'center'
      },
      tooltip: {
        trigger: 'item'
      },
      series: [{
        type: 'map',
        map: 'china',
        roam: true,
        itemStyle: {
          areaColor: '#f3f3f3',
          borderColor: '#666'
        },
        emphasis: {
          itemStyle: {
            areaColor: '#ccc'
          }
        }
      }]
    })
    // 绑定点击事件
    chart.on('click', (params) => {
      if (params.name) {
        const simpleName = simplifyProvinceName(params.name)
        selectedProvince.value = params.name
        dialogVisible.value = true
        fetchRecipes(simpleName)
      }
    })

  } catch (error) {
    console.error('地图初始化失败:', error)
  }
}

// 处理窗口大小变化
const handleResize = () => {
  chart?.resize()
}

// 组件挂载时初始化
onMounted(() => {
  initChart()
  window.addEventListener('resize', handleResize)
})

// 组件卸载时清理
onUnmounted(() => {
  chart?.dispose()
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.map-container {
  width: 100%;
  height: 100%;
  min-height: 600px;
}

.map-chart {
  width: 100%;
  height: 100%;
}

.recipe-list {
  padding: 10px;
}

.recipe-item {
  display: inline-block;
  width: 200px;
  margin: 10px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden;
  background: #fff;
}

.recipe-image {
  width: 100%;
  height: 150px;
  display: block;
}

.recipe-info {
  padding: 10px;
  text-align: center;
}

.recipe-info h3 {
  margin: 0;
  font-size: 16px;
  color: #333;
}

.recipe-info p {
  margin: 5px 0 0;
  font-size: 14px;
  color: #666;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
